package com.etheart.lyric.htmlparser.util;

import java.io.File;
import java.io.IOException;
import java.net.URLConnection;

import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.htmlparser.Parser;
import org.htmlparser.util.ParserException;

public class HtmlparserUtils {
	private static final Log logger = LogFactory.getLog(HtmlparserUtils.class);
	public static String encoding ="UTF-8";
	public static String charset ="utf-8";
	public static Parser getParser(File file) throws IOException{
		String html = FileUtils.readFileToString(file, encoding);
		return Parser.createParser(html, charset);
	}
	
	public static Parser getParser(String fileName,String url){
		File file = new File(fileName);
		if (!file.exists()) {
			Parser parser =  HtmlparserUtils.getParserFromNetWork(url);
			return parser;
		}
		String html = null;
			try {
				html = FileUtils.readFileToString(file, encoding);
			} catch (IOException e) {
				logger.debug("读取文件失败:----url:"+url+"  filename:"+fileName);
				e.printStackTrace();
			}
		return Parser.createParser(html, charset);
	}
	
	public static Parser getParserFromNetWork(String url) {
		URLConnection connection = null;
		try {
			connection= Parser.getConnectionManager().openConnection(url);
			return new Parser(connection);
		} catch (ParserException e) {
			// TODO Auto-generated catch block
			logger.debug("网络连接错误，或者parser错误:----:"+url);
			e.printStackTrace();
		}
		return null;
	}
}
